import axios from "axios";
import {ElNotification} from 'element-plus'
import {useUserInfoStore} from "@/stores/user_info";
import {ElLoading} from 'element-plus'
import router from "@/router";

let request = axios.create({
    //@ts-ignore
    timeout: 5000,
})

// let loadingInstance: any = null;

request.interceptors.request.use((config) => {
    const userInfoStore = useUserInfoStore()
    // 开启加载动画蒙层
    // loadingInstance = ElLoading.service({
    //     lock: true,
    //     text: 'Loading',
    //     background: 'rgba(0, 0, 0, 0.7)'
    // })
    if (userInfoStore.token) {
        config.headers.Authorization = userInfoStore.token
    }
    return config;
})

request.interceptors.response.use((res) => {
    // loadingInstance.close();
    return new Promise((resolve, reject) => {
        const data = res.data
        if (data.code == 200) {
            resolve(data)
        } else if (data.code == 203) {
            //后端返回需要弹窗的状态
            ElNotification({
                message: data.msg,
                duration: 2500,
                type: 'error',
            })
            reject(data)
        } else if (data.code == 10001) {
            const userInfoStore: any = useUserInfoStore()
            userInfoStore.token = null
            router.replace("/login")
        } else if (data.code == 401 || data.code == 403) {
            ElNotification({
                message: "没有权限操作",
                duration: 1500,
                type: 'error',
            })
            reject(data)
        } else {

            reject(data)
        }
    })
}, (error) => {
    // loadingInstance.close();
    ElNotification({
        message: "网络错误！请稍后重试",
        duration: 1500,
        type: 'error',
    })
})

export default request;